package com.hmall.search.Service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.hmall.common.VO.FiterVO;
import com.hmall.common.dto.FiltDTO;
import com.hmall.item.pojo.Item;
import com.hmall.item.pojo.PageResult;
import com.hmall.search.Service.SearchService;
import com.hmall.search.pojo.ItemDoc;
import com.hmall.search.pojo.RequestParams;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SearchServiceimpl implements SearchService {
    @Autowired
    private SearchService searchService;
    RestHighLevelClient client = new RestHighLevelClient(RestClient.builder(
            HttpHost.create("http://localhost:9200")));
    /**
    * @Auth: wangxinglong
    * @desc:聚合
    * @Date: 2023/6/30 15:14
    */
    @Override
    public Map<String, List<String>> getFilters(RequestParams params) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            buildBasicQuery(params, request);
            // 2.1.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2.根据分类名称，获取分类结果
            List<String> categroyList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categroyList);
            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
    }
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }
    public void buildBasicQuery(RequestParams params, SearchRequest request) {
        // 1.构建BooleanQuery
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        // 关键字搜索
        String key = params.getKey();
        if (key == null || "".equals(key)) {
            boolQuery.must(QueryBuilders.matchAllQuery());
        } else {
            boolQuery.must(QueryBuilders.matchQuery("all", key));
        }
        // 城市条件
        if (params.getCategory() != null && !params.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category", params.getCategory()));
        }
        // 品牌条件
        if (params.getBrand() != null && !params.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand", params.getBrand()));
        }
        // 价格
        if (params.getMinPrice() != null && params.getMaxPrice() != null) {
            boolQuery.filter(QueryBuilders
                    .rangeQuery("price")
                    .gte(params.getMinPrice())
                    .lte(params.getMaxPrice())
            );
        }
    }
    /**
    * @Auth: wangxinglong
    * @desc:自动补全
    * @Date: 2023/6/30 15:14
    */
    @Override
    public List<String> getSuggestions(String prefix) throws IOException {
        SearchRequest request = new SearchRequest("item");
        request.source().suggest(new SuggestBuilder().addSuggestion(
                "suggestion1",
                SuggestBuilders.completionSuggestion("suggestion")
                        .prefix(prefix)
                        .skipDuplicates(true)
                        .size(10)
        ));
        //发送请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        //解析结果
        Suggest suggest = response.getSuggest();
        //根据补全查询名称，获取补全结果
        CompletionSuggestion suggestions = suggest.getSuggestion("suggestion1");
        //获取options
        List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
        //遍历
        List<String> list = new ArrayList<>(options.size());
        for (CompletionSuggestion.Entry.Option option : options) {
            String text = option.getText().toString();
            list.add(text);
        }
        return list;
    }


//        if (filtDTO.getKey() != null && !filtDTO.getKey().equals("")) {
//            source.query(QueryBuilders.matchQuery("name", filtDTO.getKey()));
//        } else {
//            source.query(QueryBuilders.matchAllQuery());
//        }
//        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
//        request.source().from((filtDTO.getPage() - 1) * filtDTO.getSize()).size(filtDTO.getSize());
//        //判断品牌
//        if(filtDTO.getBrand() != null && !filtDTO.getBrand().equals("")) {
//            boolQuery.filter(QueryBuilders.termQuery("brand",filtDTO.getBrand()));
//        }
//        //判断分类
//        if(filtDTO.getCategory() != null && !filtDTO.getCategory().equals("")) {
//            boolQuery.filter(QueryBuilders.termQuery("category",filtDTO.getCategory()));
//        }
//        //判断价格
//        if(filtDTO.getMinPrice() != null && filtDTO.getMaxPrice()!= null) {
//            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(filtDTO.getMinPrice()).lte(filtDTO.getMaxPrice()));
//        }
//        //判断key
//        if(filtDTO.getKey()!= null && !filtDTO.getKey().equals("")){
//            boolQuery.filter(QueryBuilders.matchQuery("all",filtDTO.getKey()));
//        }
//        source.query(boolQuery);
//        try {
//            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
//            SearchHit[] hits = response.getHits().getHits();
//        //    List<FiterVO> pageList = new ArrayList<>();
//            FiterVO fiterVO=new FiterVO();
//            for (SearchHit hit : hits) {
//                // 获取文档source
//                String json = hit.getSourceAsString();
//                // 反序列化
//                FiterVO hotelDoc = JSON.parseObject(json, FiterVO.class);
//               // pageList.add(hotelDoc);
//                fiterVO.setCategory(hotelDoc.getCategory());
//                fiterVO.setBrand(hotelDoc.getBrand());
//            }
//            System.out.println(fiterVO);
//            return fiterVO;
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
//    }

    @Override
    public PageResult page(FiltDTO filtDTO) {
        SearchRequest request = new SearchRequest("item");
        SearchSourceBuilder source = request.source();
//        if (filtDTO.getKey() != null && !filtDTO.getKey().equals("")) {
//            source.query(QueryBuilders.matchQuery("name", filtDTO.getKey()));
//        } else {
//            source.query(QueryBuilders.matchAllQuery());
//        }
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        request.source().from((filtDTO.getPage() - 1) * filtDTO.getSize()).size(filtDTO.getSize());
        //判断品牌
        if(filtDTO.getBrand() != null && !filtDTO.getBrand().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("brand",filtDTO.getBrand()));
        }
        //判断分类
        if(filtDTO.getCategory() != null && !filtDTO.getCategory().equals("")) {
            boolQuery.filter(QueryBuilders.termQuery("category",filtDTO.getCategory()));
        }
        //判断价格
        if(filtDTO.getMinPrice() != null && filtDTO.getMaxPrice()!= null) {
            boolQuery.filter(QueryBuilders.rangeQuery("price").gte(filtDTO.getMinPrice()).lte(filtDTO.getMaxPrice()));
        }
        //判断key
        if(filtDTO.getKey()!= null && !filtDTO.getKey().equals("")){
            boolQuery.filter(QueryBuilders.matchQuery("all",filtDTO.getKey()));
        }
        source.query(boolQuery);
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHit[] hits = response.getHits().getHits();
            long total = response.getHits().getTotalHits().value;
            //    List<FiterVO> pageList = new ArrayList<>();
            PageResult pageResult=new PageResult();
            List pageList = new ArrayList<>();
            for (SearchHit hit : hits) {
                // 获取文档source
                String json = hit.getSourceAsString();
                // 反序列化
                ItemDoc hotelDoc = JSON.parseObject(json, ItemDoc.class);
                 pageList.add(hotelDoc);
            }
            pageResult.setTotal(total);
            pageResult.setList(pageList);
            return pageResult;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
//        PageHelper.startPage(filtDTO.getPage(),filtDTO.getSize());
//        Page<Item> itemPage=itemMapper.pageQuery();
//        PageResult pageResult=new PageResult();
//        pageResult.setTotal(itemPage.getTotal());
//        pageResult.setList(itemPage.getResult());

}
